var express = require("express");
var router = express.Router();
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();
const getToken = require("../utils/token.js");

/* 判断用户名、密码是否匹配 */
router.get("/login", async (req, res) => {
  const { name, pwd } = req.query;
  const user = await prisma.user_all.findMany({
    where: {
      user_name: name,
      user_pwd: pwd,
    },
  });
  result = {
    sign: user.length >= 1,
  };
  if (result.sign) {
    result.message = "登录成功";
    result.token = getToken(user[0]);
    if (user[0].user_role == 1)
      result.role = 1; // 管理员用户返回role
  } else result.message = "用户名或密码错误，登录失败";
  res.json(result);
});

/* 判断用户名是否已存在, 注册时用户名不能重复 */
router.get("/nameExist", async (req, res) => {
  const { name } = req.query;
  const user = await prisma.user_all.findMany({
    where: {
      user_name: {
        equals: name,
      },
    },
  });
  result = { sign: user.length == 0 }
  if (result.sign) result.message = "用户名不存在！";
  else result.message = "用户名已存在！";
  res.json(result);
});

/* 注册一个新用户, 注册页面只能注册普通用户 */
router.post("/register", async (req, res) => {
  const { name, pwd } = req.body;
  const newUser = await prisma.user_all.create({
    data: { user_name: name, user_pwd: pwd, user_role: 0 },
  });
  result = {
    sign: true,
    user: newUser,
    message: "注册成功，立即跳转登录页面！",
  };
  res.json(result);
});

module.exports = router;
